﻿Imports System.ComponentModel
Imports ATS.HelperClass

Partial Public Class ucUsers2
    Dim dbUsersTable As ATSDataClassesDataContext = New ATSDataClassesDataContext
    Dim pageIsValid As Boolean = False
    Dim editFlag As Integer


    Private Sub ucUsers_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        editFlag = EditMode.Load
        LoadUsers()
        DisableAllControls()
    End Sub

    Private Sub DisableAllControls()
        HelperClass.DisableTextBox(gridUserDetails)
        HelperClass.DisablePasswordBox(gridUserDetails)
        HelperClass.DisableCheckBox(gridUserDetails)
    End Sub
    Private Sub EnableAllControls()
        HelperClass.EnableTextBox(gridUserDetails)
        HelperClass.EnablePasswordBox(gridUserDetails)
        HelperClass.EnableCheckBox(gridUserDetails)
    End Sub
    Private Sub ClearAllControls()
        HelperClass.ClearTextBox(gridUserDetails)
        HelperClass.ClearPasswordBox(gridUserDetails)
        HelperClass.ClearCheckBox(gridUserDetails)
    End Sub

    Private Sub LoadUsers(Optional ByVal userFilter As String = "")
        Dim usersTable = From userDetails In dbUsersTable.UserTables _
                         Where userDetails.Username.ToUpper.Contains(userFilter.ToUpper) _
                         Order By userDetails.Username _
                         Select userDetails.Username, userDetails.AccountLocked, userDetails.Hashed, _
                         lbImageSource = If(userDetails.AccountLocked = "False", "/images/administration/lock_unlock.png", "/images/administration/lock.png")
        listBoxUsers.ItemsSource = usersTable
        listBoxUsers.SelectedIndex = 0
        If usersTable.Count > 0 Then
            With usersTable.First
                textboxUser.Text = .Username
                passwordboxPassword.Password = "password"
                textboxPassword.Text = .Hashed
                cbLocked.IsChecked = .AccountLocked
            End With
            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
            

        Else
            textboxUser.Text = Nothing
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
        End If
        If usersTable.Count = 1 Then
            ExpanderText.Text = usersTable.Count & " record found"
        Else
            ExpanderText.Text = usersTable.Count & " records found"
        End If

    End Sub

    Private Sub LoadSelectedUser()
        Try
            Dim selectedUsername As String = listBoxUsers.SelectedItem.username.ToString
            Dim usersTable = From userDetails In dbUsersTable.UserTables _
                         Where userDetails.Username.ToUpper.Contains(selectedUsername.ToUpper) _
                         Select userDetails.Username, userDetails.AccountLocked, userDetails.Hashed, _
                         lbImageSource = If(userDetails.AccountLocked = "False", "/images/administration/lock_unlock.png", "/images/administration/lock.png")
            With usersTable.First
                textboxUser.Text = .Username
                passwordboxPassword.Password = "password"
                textboxPassword.Text = .Hashed
                cbLocked.IsChecked = .AccountLocked
            End With
            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
        Catch ex As Exception
        End Try
    End Sub

    Private Sub searchButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchButton.Click
        LoadUsers(searchBox.Text)
    End Sub

    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        LoadUsers(searchBox.Text)
    End Sub


    Private Sub listBoxUsers_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxUsers.SelectionChanged
        LoadSelectedUser()
    End Sub

    Private Sub ucActions_AddButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.AddButtonClicked
        gridListbox.IsEnabled = False
        editFlag = EditMode.Add
        ClearAllControls()
        EnableAllControls()
    End Sub

    Private Sub ucActions_CancelButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.CancelButtonClicked
        editFlag = EditMode.Load
        DisableAllControls()
        LoadSelectedUser()
        gridListbox.IsEnabled = True
    End Sub

    Private Sub ucActions_DeleteButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.DeleteButtonClicked
        Dim warningString As String = "Do you really want to delete this record?" & ControlChars.Lf & listBoxUsers.SelectedItem.username.ToString
        If System.Windows.MessageBox.Show(warningString, "Delete Record", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
            Dim selectedUsername As String = listBoxUsers.SelectedItem.username.ToString
            Dim usersTable = From userDetails In dbUsersTable.UserTables _
                         Where userDetails.Username.ToUpper = (selectedUsername.ToUpper)
            Dim exst As UserTable = usersTable.First
            dbUsersTable.UserTables.DeleteOnSubmit(exst)
            dbUsersTable.SubmitChanges()
            LoadUsers()
        End If
    End Sub

    Private Sub ucActions_EditButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.EditButtonClicked
        editFlag = EditMode.Edit
        gridListbox.IsEnabled = False
        EnableAllControls()
        textboxUser.IsEnabled = False
        passwordboxPassword.Password = Nothing
    End Sub

    Private Sub ucActions_SaveButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.SaveButtonClicked
        Try
            If pageIsValid Then
                Dim ListBoxSelectedItemIndex As Integer = listBoxUsers.SelectedIndex
                Dim saltUsed As Byte() = GencPros_Authenticate.EncryptDecrypt.ComputeSalt
                If editFlag = EditMode.Edit Then
                    Dim usersTable = From userDetails In dbUsersTable.UserTables _
                                 Where userDetails.Username.ToUpper = textboxUser.Text.ToUpper

                    With usersTable.First
                        .Hashed = GencPros_Authenticate.EncryptDecrypt.ComputeHash(passwordboxPassword.Password, "SHA512", saltUsed)
                        .AccountLocked = cbLocked.IsChecked
                        .Salt = Convert.ToBase64String(saltUsed)
                    End With
                    dbUsersTable.SubmitChanges()
                ElseIf editFlag = EditMode.Add Then
                    Dim saveNewUser As New UserTable


                    With saveNewUser
                        .Salt = Convert.ToBase64String(saltUsed)
                        .Username = textboxUser.Text
                        .Hashed = GencPros_Authenticate.EncryptDecrypt.ComputeHash(passwordboxPassword.Password, "SHA512", saltUsed)
                        .AccountLocked = cbLocked.IsChecked
                    End With
                    dbUsersTable.UserTables.InsertOnSubmit(saveNewUser)
                    dbUsersTable.SubmitChanges()
                End If
                editFlag = EditMode.Load

                If searchBox.Text.Length > 0 Then
                    LoadUsers(searchBox.Text)
                Else
                    LoadUsers()
                End If

                listBoxUsers.SelectedIndex = ListBoxSelectedItemIndex
                DisableAllControls()
                gridListbox.IsEnabled = True
            Else
                ucActions.buttonSaveMain.IsEnabled = True
                ucActions.buttonEditMain.IsEnabled = False
                ucActions.buttonAddMain.IsEnabled = False
                ucActions.buttonDeleteMain.IsEnabled = False
                ucActions.buttonCancelMain.IsEnabled = True
            End If
        Catch ex As Exception
            CheckForSQLErrors(ex)
            ucActions.buttonSaveMain.IsEnabled = True
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonAddMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
            ucActions.buttonCancelMain.IsEnabled = True
        End Try
    End Sub


    Private Sub passwordboxPassword_PasswordChanged(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles passwordboxPassword.PasswordChanged
        pageIsValid = EntryValidation.ValidatePassword(passwordboxPassword)
    End Sub

    Private Sub textboxUser_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxUser.TextChanged
        pageIsValid = EntryValidation.ValidateText(sender)
        If editFlag = EditMode.Add Then
            Dim selectedUsername As String = textboxUser.Text.ToString
            Dim usersTable = From userDetails In dbUsersTable.UserTables _
                         Where userDetails.Username = selectedUsername.ToUpper
            If usersTable.Count > 0 And textboxUser.IsEnabled = True Then
                pageIsValid = False
                textboxUser.BorderBrush = New SolidColorBrush(Colors.Red)
                textboxUser.ToolTip = "Username already exist."
            End If
        End If
    End Sub

End Class



